﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Drawing.Imaging;
using System.Drawing;
using System.Data;
using System.Data.OleDb;
using System.Web.UI;
using OfficeOpenXml;

namespace Heyu.Utility
{

    #region 上传文件的属性类

    /// <summary>
    /// 上传文件的属性
    /// </summary>
    public class UploadAttribute
    {
        private FileType _filetype = FileType.Image;
        private string _savepath = "images";
        private int _size = 2;
        private bool _allownull = true;
        private string _rename = "";

        /// <summary>
        /// 上传控件
        /// </summary>
        public FileUpload FileUpload { get; set; }
        /// <summary>
        /// 文件类型（默认图片）
        /// </summary>
        public FileType FileType
        {
            get { return _filetype; }
            set { _filetype = value; }
        }
        /// <summary>
        /// 保存路径(如：uploads/images)
        /// </summary>
        public string SavePath
        {
            get { return _savepath; }
            set { _savepath = value; }
        }
        /// <summary>
        /// 文件大小（默认2M）
        /// </summary>
        public int Size
        {
            get { return _size; }
            set { _size = value; }
        }
        /// <summary>
        /// 是否允许为空（默认允许为空）
        /// </summary>
        public bool AllowNull
        {
            get { return _allownull; }
            set { _allownull = value; }
        }
        /// <summary>
        /// 空或者“rename”-重命名（按日期），“filename”-文件原始名称，其他-指定名称
        /// </summary>
        public string ReName
        {
            get { return _rename; }
            set { _rename = value; }
        }
        /// <summary>
        /// 缩略图格式
        /// </summary>
        public string[] ArrThumbnail { get; set; }
        /// <summary>
        /// 生成缩略图的格式（HW、W、H、Cut、Fill）
        /// </summary>
        public string ThumbnailMode { get; set; }
    }

    #endregion

    /// <summary>
    /// 文件操作类
    /// </summary>
    public class FileUtility
    {
        public FileUtility()
        {
        }

        #region 文件上传

        /// <summary>
        /// 检查文件类型是否包含在指定类型中
        /// </summary>
        /// <param name="fileContentType"></param>
        /// <param name="extensions"></param>
        /// <returns></returns>
        public static bool checkFileType(string fileContentType, string[] extensions)
        {
            bool flag = false;
            for (int i = 0; i < extensions.Length; i++)
            {
                if (fileContentType == extensions[i])
                {
                    flag = true;
                }
            }
            return flag;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileupload"></param>
        /// <param name="upload"></param>
        /// <param name="res">输出结果（如果上传成功，返回文件名，失败则返回错误信息）</param>
        /// <returns></returns>
        public static bool FileUpload(UploadAttribute upload, out string res)
        {
            //filepath = upload.FilePath;//获取文件路径
            //filename = System.IO.Path.GetDirectoryName(filepath);//根据路径获取完整的文件名
            //name = filename.Substring(0, filename.LastIndexOf('.'));//不含扩展名的名称
            //fileContentType = System.IO.Path.GetExtension(filename).ToLower(); ;//扩展名

            //FileInfo file = new FileInfo(filepath);
            //length_B = file.Length;


            FileUpload fileupload = upload.FileUpload;

            res = "";
            if (upload.AllowNull)
            {
                if (fileupload.PostedFile.FileName == "")
                {
                    return true;
                }
            }
            else
            {
                if (fileupload.PostedFile.FileName == "")
                {
                    res = "请选择文件！";
                    return false;
                }
            }

            //string filename = FileUpload1.PostedFile.FileName;//全名--------测试发现，IE11浏览器获取的的路径加名称，360浏览器获取的是文件名称，如：C:\Users\HeYu\Desktop\9D6FE94000CD02CABA63486EA3CA427C.jpg
            string filename = fileupload.FileName;
            string name = filename.Substring(0, filename.LastIndexOf('.'));//不含扩展名的名称
            string filepath = fileupload.PostedFile.FileName;
            //string fileContentType = FileUpload1.PostedFile.ContentType;//扩展名--image/pjpeg
            //string fileContentType = filename.Substring(filename.LastIndexOf(".")).ToLower();//扩展名
            string fileContentType = System.IO.Path.GetExtension(filename).ToLower(); ;//扩展名


            double length_B = fileupload.PostedFile.ContentLength;
            double length_MB = length_B / (1024 * 1024);
            if (length_MB >= upload.Size)
            {
                res = "上传的文件必须小于" + upload.Size + "MB!";
                return false;
            }

            switch (upload.FileType)
            {
                case FileType.Image:
                    if (!checkFileType(fileContentType, DataTypeUtility.imgExtensions))
                    {
                        res = "文件格式不正确，只能上传：" + StringUtility.ArrToString(DataTypeUtility.imgExtensions) + "的格式文件！";
                        return false;
                    }
                    break;
                case FileType.Package:
                    if (!checkFileType(fileContentType, DataTypeUtility.packageExtensions))
                    {
                        res = "文件格式不正确，只能上传：" + StringUtility.ArrToString(DataTypeUtility.packageExtensions) + "的格式文件！";
                        return false;
                    }
                    break;
                case FileType.Flash:
                    if (!checkFileType(fileContentType, DataTypeUtility.packageExtensions))
                    {
                        res = "文件格式不正确，只能上传：" + StringUtility.ArrToString(DataTypeUtility.flashExtensions) + "的格式文件！";
                        return false;
                    }
                    break;
                case FileType.Audio:
                    if (!checkFileType(fileContentType, DataTypeUtility.packageExtensions))
                    {
                        res = "文件格式不正确，只能上传：" + StringUtility.ArrToString(DataTypeUtility.audioExtensions) + "的格式文件！";
                        return false;
                    }
                    break;
                case FileType.Video:
                    if (!checkFileType(fileContentType, DataTypeUtility.packageExtensions))
                    {
                        res = "文件格式不正确，只能上传：" + StringUtility.ArrToString(DataTypeUtility.videoExtensions) + "的格式文件！";
                        return false;
                    }
                    break;
                case FileType.Excel:
                    if (!checkFileType(fileContentType, DataTypeUtility.excelExtensions))
                    {
                        res = "文件格式不正确，只能上传：" + StringUtility.ArrToString(DataTypeUtility.excelExtensions) + "的格式文件！";
                        return false;
                    }
                    break;
                default:
                    res = "文件类型不正确：不支持该文件的上传！";
                    return false;
            }


            #region 重命名文件
            string saveName = "";
            switch (upload.ReName.ToLower())
            {
                case "":
                    goto case "rename";
                case "rename":
                    saveName = DateTime.Now.ToString("yyyyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileContentType;
                    break;
                case "filename":
                    saveName = getNewFilename(upload.SavePath, name, fileContentType);
                    break;
                default:
                    saveName = upload.ReName;
                    break;
            }
            #endregion

            //在指定的目录上保存上传的文件
            string fPath = HttpContext.Current.Server.MapPath("~/" + upload.SavePath);//文件夹绝对路径
            if (!Directory.Exists(fPath)) //如果文件夹不存在则创建
            {
                Directory.CreateDirectory(fPath);
            }

            string sourcePath = HttpContext.Current.Server.MapPath("~/" + Path.Combine(upload.SavePath, saveName));//文件绝对路径
            fileupload.SaveAs(sourcePath);

            #region 生成缩略图

            //string spath_watermark = HttpContext.Current.Server.MapPath(path + "/watermark/" + newName);
            //string spath_source = HttpContext.Current.Server.MapPath("~/uploads/images/shuiyin.png");　// 服务器端水印图路径(图片)



            if (upload.FileType == FileType.Image && upload.ArrThumbnail != null)
            {
                for (int i = 0; i < upload.ArrThumbnail.Length; i++)
                {
                    string[] arr_w_h = upload.ArrThumbnail[i].ToString().Split('*');//缩略图
                    int width = 0;
                    int height = 0;
                    if (arr_w_h.Length == 1)
                    {
                        width = Convert.ToInt32(arr_w_h[0]);
                    }
                    if (arr_w_h.Length == 2)
                    {
                        width = Convert.ToInt32(arr_w_h[0]);
                        height = Convert.ToInt32(arr_w_h[1]);
                    }

                    //AddShuiYinWord(spath, spath_watermark);
                    //AddShuiYinPic(spath, spath_watermark, spath_source);

                    //MakeThumbnail(newName, upload.SavePath, upload.SavePath + "/" + width + "_" + height, width, height, upload.ThumbnailMode);
                    string savePath = HttpContext.Current.Server.MapPath("~/" + upload.SavePath + "/" + width + "_" + height);
                    ImageUtility.SaveThumbnail(sourcePath, savePath, saveName, width, height, upload.ThumbnailMode);
                }
            }
            #endregion

            res = saveName;
            return true;
        }



        /// <summary>
        /// 检查文件名称是否存在，如果存在重命名并返回名称
        /// </summary>
        /// <param name="path"></param>
        /// <param name="filename"></param>
        /// <param name="filetype"></param>
        /// <returns></returns>
        public static string getNewFilename(string path, string filename, string filetype)
        {
            string first_filename = filename;//记录第一次的文件名称，以后重命名以此为基础。
            for (int i = 2; i < 100; i++)
            {
                string pathname = HttpContext.Current.Server.MapPath(Path.Combine(path, filename, filetype));
                if (File.Exists(pathname)) //如果文件名已存在
                {
                    filename = first_filename + "(" + i + ")";
                }
                else
                {
                    break;
                }
            }
            return filename + filetype;
        }

        #endregion

        #region 下载
        /// <summary>
        /// 从互联网地址保存图片
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        /// <param name="name"></param>
        public static void saveFileFromInternet(string url, string path, string name)
        {
            //http://up.2cto.com/2012/0516/20120516112717995.gif  //测试图片途径
            WebRequest wreq = WebRequest.Create(url);
            HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
            Stream s = wresp.GetResponseStream();
            System.Drawing.Image img;
            img = System.Drawing.Image.FromStream(s);
            img.Save(HttpContext.Current.Server.MapPath(path) + name, ImageFormat.Jpeg);   //保存
        }


        public static string savePhotoFromByte(byte[] bt, string path)
        {
            string wpath = HttpContext.Current.Server.MapPath(path);
            if (!Directory.Exists(wpath))
            {
                Directory.CreateDirectory(wpath);
            }

            //将byte[]形式转换成MemoryStream形式，再保存为图片

            System.IO.MemoryStream ms = new System.IO.MemoryStream(bt);
            System.Drawing.Bitmap b = new System.Drawing.Bitmap(ms);

            string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond;
            string filetype = ".jpg";

            filename = FileUtility.getNewFilename(path, filename, filetype);
            b.Save(wpath + filename + filetype);

            return filename + filetype;
        }
        ///<summary>
        /// Web下载文件
        ///</summary>
        ///<param name="physicalPath">要下载文件的物理路径</param>
        ///<param name="contentType">文件类型，如 excel是 application/vnd.ms-excel word 是application/msword</param>
        public static void DownloadFile(string physicalPath, string contentType)
        {

            HttpContext.Current.Response.Clear();

            // Buffer to read 10K bytes in chunk:
            byte[] buffer = new Byte[10000];

            // Length of the file:
            int length;

            // Total bytes to read:
            long dataToRead;

            string filename = Path.GetFileName(physicalPath);
            using (Stream iStream = new FileStream(physicalPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                // Total bytes to read:
                dataToRead = iStream.Length;
                HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
                HttpContext.Current.Response.ContentType = contentType;
                HttpContext.Current.Response.AddHeader("Content-Length", iStream.Length.ToString());
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, Encoding.UTF8));

                // Read the bytes.
                while (dataToRead > 0)
                {
                    // Verify that the client is connected.
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        // Read the data in buffer.
                        length = iStream.Read(buffer, 0, 10000);

                        // Write the data to the current output stream.
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);

                        // Flush the data to the HTML output.
                        //HttpContext.Current.Response.Flush();// 测试服务器无法在发送 HTTP 标头之后追加标头
                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        //prevent infinite loop if user disconnects
                        dataToRead = -1;
                    }
                }

            }

        }
        #endregion

        #region 生成静态页面

        /// <summary>
        /// 生成静态页面
        /// </summary>
        /// <param name="url"></param>
        /// <param name="htmName"></param>
        public static void writeHtml(string url, string htmName)
        {
            System.IO.StreamWriter sw = new System.IO.StreamWriter(System.Web.HttpContext.Current.Server.MapPath(@"~/" + htmName), false, System.Text.Encoding.UTF8);
            System.Web.HttpContext.Current.Server.Execute(@"~/" + url, sw);
            sw.Close();
        }

        /// <summary>
        /// 创建html
        /// </summary>
        /// <param name="url"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public static void CreateHtml(string url, string savePath)
        {
            //string url = "http://localhost:4710/Area/set";//
            //path = Server.MapPath(path);//
            WebRequest request = WebRequest.Create(url);
            try
            {
                Stream stream = request.GetResponse().GetResponseStream();
                StreamReader sr = new StreamReader(stream, Encoding.UTF8);
                string htmlcontent = sr.ReadToEnd();
                stream.Close();
                sr.Close();
                SaveToFile(savePath, htmlcontent);
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 将字符串保存到文件中请求一个文件（保存静态页）
        /// </summary>
        /// <param name="path"></param>
        /// <param name="content"></param>
        public static void SaveToFile(string savePath, string content)
        {
            try
            {
                string dirPath = Path.GetDirectoryName(savePath);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                sw.Write(content);
                sw.Close();
                fs.Close();
            }
            catch (Exception ex)
            {

            }

        }

        #endregion

        #region 数据导入
        /// <summary>
        /// 获取Excel表的数据
        /// 需加表头，否则第一行数据会被认做表头
        /// </summary>
        /// <param name="fileurl">文件路径（绝对路径）</param>
        /// <param name="table"></param>
        /// <returns></returns>
        public static DataSet GetExcelDataSet(string fileurl)
        {
            DataSet ds = new DataSet();//输入的DataSet
            string ConnectionString = "";


            //Extended Properties='Excel 8.0;hdr=no;IMEX=1';
            //HDR=NO即无字段 HDR=yes　即有字段，一般默认excel表中第1行的列标题为字段名，如姓名、年龄等  默认值是Yes
            //IMEX　表示是否强制转换为文本
            //0 ---输出模式;
            //1---输入模式;
            //2----链接模式(完全更新能力)


            //HDR=Yes，这代表第一行是标题，不做为数据使用；IMEX ( IMport EXport mode )设置
            //IMEX 有三种模式：
            //0 is Export mode
            //1 is Import mode
            //2 is Linked mode (full update capabilities)
            //我这里特别要说明的就是 IMEX 参数了，因为不同的模式代表著不同的读写行为：
            //当 IMEX=0 时为“汇出模式”，这个模式开启的 Excel 档案只能用来做“写入”用途。
            //当 IMEX=1 时为“汇入模式”，这个模式开启的 Excel 档案只能用来做“读取”用途。
            //当 IMEX=2 时为“连结模式”，这个模式开启的 Excel 档案可同时支援“读取”与“写入”用途。
            //  意义如下:
            //  0 ---输出模式;
            //  1---输入模式;
            //  2----链接模式(完全更新能力)


            //获取Excel路径 
            FileInfo info = new FileInfo(fileurl);
            //获取文件的扩展名 
            string fileExt = info.Extension;
            //判断用哪种连接方式 
            if (fileExt.ToLower() == ".xls")
            {
                ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileurl + ";Extended Properties='excel 8.0;';Persist Security Info=false";
            }
            else if (fileExt.ToLower() == ".xlsx")
            {
                ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + fileurl + ";Extended Properties='excel 12.0 Xml;';Persist Security Info=False";
            }
            //连接excel 
            OleDbConnection conn = new OleDbConnection(ConnectionString);
            //打开excel 
            conn.Open();


            DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);//获取所有的Excel表信息



            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string TableName = dt.Rows[i]["TABLE_NAME"].ToString();

                OleDbDataAdapter da = new OleDbDataAdapter("select * from [" + TableName + "]", conn);

                da.Fill(ds, TableName); //把数据填充到Dataset 

            }

            conn.Close();


            return ds; //反回Dataset 

        }


        /// <summary>
        /// 获取fileupload选择的文件的数据
        /// 1、上传文件到服务器
        /// 2、调用GetExcelDataSet(string fileurl)方法
        /// 需加表头，否则第一行数据会被认做表头
        /// </summary>
        /// <param name="fileupload"></param>
        /// <param name="error">输入错误信息</param>
        /// <returns></returns>
        public static DataSet GetExcelDataSet(FileUpload fileupload, out string res)
        {
            DataSet ds = new DataSet();
            res = "";

            UploadAttribute ua = new UploadAttribute();
            ua.FileUpload = fileupload;
            ua.FileType = FileType.Excel;
            ua.SavePath = "uploads/Excel";
            ua.Size = 10;
            ua.ReName = "filename";
            ua.AllowNull = false;
            if (FileUpload(ua, out res))
            {
                try
                {
                    string spath = HttpContext.Current.Server.MapPath("~/" + ua.SavePath + "/" + res);
                    ds = GetExcelDataSet(spath);
                }
                catch (Exception ex)
                {
                    res = ex.Message.ToString();
                }
            }

            return ds;
        }

        /// <summary>
        /// 获取数据导入的SQL语句
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="table">表名</param>
        /// <param name="column">列名，用逗号(,)分隔</param>
        /// <returns></returns>
        public string GetDataImportSQL(DataTable dt, string table, string column)
        {
            string sql = "";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sql += " inser into " + table + "(" + column + ")";
                sql += " values(";
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (j == 0)
                    {
                        sql += "'" + dt.Rows[i][j].ToString() + "'";
                    }
                    else
                    {
                        sql += ",'" + dt.Rows[i][j].ToString() + "'";
                    }
                }
                sql += ")";
            }

            return sql;
        }

        #endregion

        #region 数据导出

        //1）  文本：vnd.ms-excel.numberformat:@

        //2）  日期：vnd.ms-excel.numberformat:yyyy/mm/dd

        //3）  数字：vnd.ms-excel.numberformat:#,##0.00

        //4）  货币：vnd.ms-excel.numberformat:￥#,##0.00

        //5）  百分比：vnd.ms-excel.numberformat: #0.00%


        /// <summary>
        /// 在服务器指定路径创建Excel表格
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="path">生成Excel的路径</param>
        /// <param name="filename">文件名称</param>
        public static void ExcelCreate(DataTable dt, string path, string filename)
        {
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); //调用Excel组件
            Microsoft.Office.Interop.Excel.Workbook excelbook = excel.Application.Workbooks.Add(true);//在Excel中添加一个工作簿
            excel.Visible = false;//设置Excel是否显示

            //生成字段名称
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                excel.Cells[1, i + 1] = dt.Columns[i].Caption;//将数据表格控件中的列表头填充到Excel中
            }
            //填充数据
            for (int i = 0; i < dt.Rows.Count; i++)//遍历数据表格控件的所有行
            {
                for (int j = 0; j < dt.Columns.Count; j++)//遍历数据表格控件的所有列
                {
                    if (dt.Rows[i][j].GetType() == typeof(string))//判断遍历到的数据是否是字符串类型
                    {
                        excel.Cells[i + 2, j + 1] = "'" + dt.Rows[i][j].ToString();//填充Excel表格
                    }
                    else
                    {
                        excel.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();//填充Excel表格
                    }
                }
            }
            object missing = System.Reflection.Missing.Value; //设置默认值，在之后的参数填充中使用
            excel.DisplayAlerts = false; //设置不显示弹出对话框
            excel.AlertBeforeOverwriting = false; //设置无提示直接重写文件
            //excel.Application.Workbooks.Add(true).Save();

            //string wpath = ("E:\\" + spath);
            string wpath = HttpContext.Current.Server.MapPath(path);
            string spath = HttpContext.Current.Server.MapPath(path + "/" + filename);
            if (!Directory.Exists(wpath)) //如果文件夹不存在则创建
            {
                Directory.CreateDirectory(wpath);
            }


            excelbook.SaveAs(spath, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing,
                 missing, missing, missing, missing); //XlFileFormat.xlExcel8是2003格式，xlOpenXMLWorkbook是2007格式，查了不少资料才搞清楚，

            excelbook.Close(true, spath, false); //关闭工作簿

            excel.Quit(); //退出Excel
            //excel = null;   //这句话理论上应该有用，但是实际没有。Excel进程依然存在，没有结束的迹象。只能杀进程。  
        }


        public static void ExcelCreater2()
        {
            var file = HttpContext.Current.Server.MapPath("~/Sample.xlsx");
            if (File.Exists(file)) File.Delete(file);



            using (var excel = new ExcelPackage(new FileInfo(file)))
            {
                var ws = excel.Workbook.Worksheets.Add("Sheet1");
                ws.Cells[1, 1].Value = "Date";
                ws.Cells[1, 2].Value = "Price";
                ws.Cells[1, 3].Value = "Volume";
                var random = new Random();
                for (int i = 0; i < 10; i++)
                {
                    ws.Cells[i + 2, 1].Value = DateTime.Today.AddDays(i);
                    ws.Cells[i + 2, 2].Value = random.NextDouble() * 1e3;
                    ws.Cells[i + 2, 3].Value = random.Next() / 1e3;
                }

                ws.Cells[2, 1, 11, 1].Style.Numberformat.Format = "dd/MM/yyyy";
                ws.Cells[2, 2, 11, 2].Style.Numberformat.Format = "#,##0.000000";
                ws.Cells[2, 3, 11, 3].Style.Numberformat.Format = "#,##0";
                ws.Column(1).AutoFit();
                ws.Column(2).AutoFit();
                ws.Column(3).AutoFit();
                excel.Save();
            }
        }

        /// <summary>
        /// 导出到Excel（直接输出DataTable）
        /// </summary>
        /// <param name="pData">DataTable</param>
        /// <param name="pFileName">导出文件名</param>
        /// <param name="pHeader">导出标题以|分割</param>
        public static void ExcelExport(DataTable dt, string pFileName)
        {
            System.Web.UI.WebControls.DataGrid dgExport = null;
            // 当前对话 
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            // IO用于导出并返回excel文件 
            System.IO.StringWriter strWriter = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;
            if (dt != null)
            {
                string UserAgent = curContext.Request.ServerVariables["http_user_agent"].ToLower();
                if (UserAgent.IndexOf("firefox") == -1)//火狐浏览器

                    pFileName = HttpUtility.UrlEncode(pFileName, System.Text.Encoding.UTF8);

                curContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + pFileName + ".xls");
                curContext.Response.ContentType = "application/vnd.ms-excel";
                curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
                curContext.Response.Charset = "";

                strWriter = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                // 为了解决dgData中可能进行了分页的情况，需要重新定义一个无分页的DataGrid 
                dgExport = new System.Web.UI.WebControls.DataGrid();
                dgExport.DataSource = dt.DefaultView;
                dgExport.AllowPaging = false;
                dgExport.ShowHeader = true;//是否显示标题
                dgExport.DataBind();

                // 返回客户端 
                dgExport.RenderControl(htmlWriter);

                curContext.Response.Write(strWriter.ToString());
                curContext.Response.End();
            }
        }
        /// <summary>
        /// 导出Excel表格（自定义画表格）
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pFileName"></param>
        /// <param name="pHeader"></param>
        public static void ExcelExportOfDrawing(DataTable dt, string filename, string headers)
        {
            if (dt != null)
            {
                #region 根据DataTable 生成Table html代码
                string[] arrHeader = headers.Split('|');

                StringBuilder sb = new StringBuilder();
                sb.Append("<table border=\"1\" style=\"text-align:center;\"><tr>");
                foreach (string header in arrHeader)
                {
                    sb.Append("<td>" + header.ToString() + "</td>");
                }
                sb.Append("</tr>");

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    sb.Append("<tr>");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        sb.Append("<td style=\"vnd.ms-excel.numberformat:@; text-align:center;\">");
                        sb.Append(dt.Rows[i][j].ToString().Trim());
                        sb.Append("</td>");
                    }
                    sb.Append("</tr>");
                }
                sb.Append("</table>");

                #endregion

                ExcelExportOfDrawing(filename, sb.ToString());
            }
        }
        /// <summary>
        /// 导出Excel表格(自定义table)
        /// </summary>
        /// <param name="filename">文件名称</param>
        /// <param name="body">table html代码</param>
        public static void ExcelExportOfDrawing(string filename, string body)
        {
            string meta = "<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=UTF-8\"/>";

            string UserAgent = HttpContext.Current.Request.ServerVariables["http_user_agent"].ToLower();//获取浏览器

            if (UserAgent.IndexOf("firefox") == -1)//火狐浏览器
                filename = HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + ".xls");
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.Charset = "";
            HttpContext.Current.Response.Write(meta + body);
            HttpContext.Current.Response.End();
        }

        //方法ExportControl(System.Web.UI.Control source, string DocumentType,string filename)中
        //第一个参数source表示导出的页面或控件名,当为datagrid或dataList控件时，在导出Excel/word文件时，必须把控件的分页、排序等属性去除并重新绑定，
        //第二个参数DocumentType表示导出的文件类型word或excel
        //第三个参数filename表示需要导出的文件所取的文件名
        //调用方法：
        //ExportData export=new ExportData();
        //export.ExportControl(this, "Word","testfilename");//当为this时表示当前页面
        //这是将整个页面导出为Word,并命名为testfilename

        /// <summary>
        /// 将Web控件或页面信息导出(不带文件名参数)
        /// </summary>
        /// <param name="source">控件实例</param>        
        /// <param name="DocumentType">导出类型:Excel或Word</param>
        public void ExportControl(System.Web.UI.Control source, string DocumentType)
        {
            //设置Http的头信息,编码格式
            if (DocumentType == "Excel")
            {
                //Excel            
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("下载文件.xls", System.Text.Encoding.UTF8));
                HttpContext.Current.Response.ContentType = "application/ms-excel";
            }
            else if (DocumentType == "Word")
            {
                //Word
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("下载文件.doc", System.Text.Encoding.UTF8));
                HttpContext.Current.Response.ContentType = "application/ms-word";
            }

            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;

            //关闭控件的视图状态
            source.Page.EnableViewState = false;


            //初始化HtmlWriter
            System.IO.StringWriter writer = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
            source.RenderControl(htmlWriter);

            //输出
            HttpContext.Current.Response.Write(writer.ToString());
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 将Web控件或页面信息导出(带文件名参数)
        /// </summary>
        /// <param name="source">控件实例</param>        
        /// <param name="DocumentType">导出类型:Excel或Word</param>
        /// <param name="filename">保存文件名</param>
        public void ExportControl(System.Web.UI.Control source, string DocumentType, string filename)
        {
            //设置Http的头信息,编码格式
            if (DocumentType == "Excel")
            {
                //Excel            
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".xls", System.Text.Encoding.UTF8));
                HttpContext.Current.Response.ContentType = "application/ms-excel";
            }

            else if (DocumentType == "Word")
            {
                //Word
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".doc", System.Text.Encoding.UTF8));
                HttpContext.Current.Response.ContentType = "application/ms-word";
            }

            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;

            //关闭控件的视图状态
            source.Page.EnableViewState = false;

            //初始化HtmlWriter
            System.IO.StringWriter writer = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
            source.RenderControl(htmlWriter);

            //输出
            HttpContext.Current.Response.Write(writer.ToString());
            HttpContext.Current.Response.End();
        }
        #endregion

        #region 文本操作

        /// <summary>
        /// 记录文本日志
        /// </summary>
        /// <param name="path">记录日志的路径（相对路径，从根目录开始，如：uploads/excel）</param>
        /// <param name="name">文件名称(不需要加后缀名)</param>
        /// <param name="log">日志内容</param>
        public static void WriteLog(string path, string name, string log)
        {
            string wpath = HttpContext.Current.Server.MapPath("~/" + path);
            string spath = HttpContext.Current.Server.MapPath("~/" + path + "/" + name + ".txt");

            if (!Directory.Exists(wpath))
            {
                Directory.CreateDirectory(wpath);
            }
            StreamWriter sr = null;


            try
            {
                if (!File.Exists(spath))
                {
                    sr = File.CreateText(spath);
                }
                else
                {
                    sr = File.AppendText(spath);
                }

                sr.WriteLine(log + "\r\n\r\n");//strMemo
            }
            catch (Exception ex)
            {
                string error = "错误！错误原因：" + ex.Message + "\r\n\r\n";
                sr.WriteLine(error);//strMemo
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }

        }
        #endregion

    }
}
